import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Class of SocketServer, which provides service, such as creating an object of ClientWorker class for each client.
 * @author Agnieszka Rucinska
 *  
 */

class SocketServer extends Thread
{
	ServerSocket server = null;
	BufferedReader in = null;
	PrintWriter out = null;
	Socket client = null;
	Game game = null;
	
	
	SocketServer(int port, Game game)
	{
		try
		{
			this.game = game;
			server = new ServerSocket(port);
			System.out.println("Server on port " + server.getLocalPort()
					+ " started Jupi!.");
		}
		catch (IOException e)
		{
			System.out.println("Could not listen on port " + port +".");
			System.exit(-1);
		}
	}

	/**
	 * method loops on the server, accept call waiting for client connections and creates an instance of the Player class
	 *  for each client connection it accepts.
	 */
	public void run()
	{
		try
		{
			client = server.accept();
			System.out.println("Client " + client.getInetAddress()+"  "+ client.getPort() + " accepted on port.");
		} 
		catch (IOException e)
		{
			System.out.println("Accept failed:" + client.getInetAddress());
			System.exit(-1);
		}
		System.out.println("Zaraz utworze playera");
		game.sitPlayer("testplayer", client);
	}
	
	protected void finalize()
	{
		try
		{
			in.close();
			out.close();
			server.close();
		} catch (IOException e)
		{
			System.out.println("Could not close.");
			System.exit(-1);
		}
	}
}
